/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package alcatelparser;

import alcatelparser.errors.ParseFailedException;
import alcatelparser.modules.ApplicationSettings;
import alcatelparser.modules.Parser;
import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FileTransferClient;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;


/**
 *
 * @author geniuz
 */
public class Main {

    
    /**
     * @param args the command line arguments
     */

    
    private static ApplicationSettings aps;
    private static String GetFileName(){
        Date dt=new Date();
        dt.setHours(dt.getHours()-3);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH00.H");
        String s = "USBSPC." + sdf.format(dt);
        return s;
        
    }
    
    public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException, FTPException {
        
        aps = ApplicationSettings.getInstance();
        String dbhost = aps.getProperty("dbpass");
        
        String filename  = GetFileName();
        
        
        //String pguser = "pg_admin";
        //String pgpass = "[jxe100,jxtrgbdf";
        Class.forName("org.postgresql.Driver"); //load the driver
        Connection db = DriverManager.getConnection("jdbc:postgresql://" + aps.getProperty("dbhost")+"/"+aps.getProperty("dbname"),aps.getProperty("dbuser"),aps.getProperty("dbpass")); //connect to the db
        DatabaseMetaData  dbmd = db.getMetaData(); //get MetaData to confirm connection
        Statement stmt = db.createStatement();

        String selquery = "select filename from conversions where converted = '0' and substring(filename from 1 for 1)='U'";
        ResultSet rs = stmt.executeQuery(selquery);
        while (rs.next())
        {
            String fn = rs.getString("filename");
            DownloadAndParse(fn);
        }
        
        
        String sqlquery = "insert into conversions (filename, converted) values ('" + filename + "', '0')";
        stmt.executeUpdate(sqlquery);
        
        DownloadAndParse(filename);


    }
    private static void DownloadAndParse(String filename) throws ClassNotFoundException, SQLException, FTPException, IOException{
        
        //String hostname = "192.168.20.147", username = "bill_ftp", password = "bill_ftp";
        FileTransferClient ftpc = new FileTransferClient();
        ftpc.setRemoteHost(aps.getProperty("ftphost"));
        ftpc.setUserName(aps.getProperty("ftpuser"));
        ftpc.setPassword(aps.getProperty("ftppass"));
        
        System.out.println("file: "+filename);
        
        File f = new File(filename);
        if (!f.exists())
        {
            ftpc.connect();
            ftpc.changeDirectory(aps.getProperty("ftpdir"));
            String[] files = ftpc.directoryNameList();
            ArrayList dd = new ArrayList();
            Collections.addAll(dd, files);
            if (dd.contains(filename))
            {
                System.out.println("exists in ftp, downloading");
                ftpc.downloadFile(filename,filename);
                f = new File(filename);
                System.out.println("downloaded");
            }
            else {
                System.out.println("not exists in ftp");
            }
            
            ftpc.disconnect();
            
        }
        /*
        Ftp ftp = new Ftp(aps.getProperty("ftphost"),aps.getProperty("ftpuser"),aps.getProperty("ftppass"));

        System.out.println("file: "+filename);
        File f = new File(filename);
        if (!f.exists())
        {
            ftp.connect();
            ftp.setDir(aps.getProperty("ftpdir"));
            ArrayList dd = Collections.list(ftp.getNameListing());
            if (dd.contains(filename))
            {
                System.out.println("exists in ftp, downloading");
                f = ftp.download(filename,filename);
                System.out.println("downloaded");
            }
            else {
                System.out.println("not exists in ftp");
            }
            ftp.disconnect();
        }*/
        if (f.exists())        
        {
            Parser parser=new Parser();
            try {
                System.out.println("Starting");
                parser.startParse(f);
                System.out.println("End");
                System.out.println("Parsed " + parser._currentRecord + " records");
                System.out.println("Query started");
                Process process = Runtime.getRuntime().exec("psql -d "+aps.getProperty("dbname")+" -f tmp.tmp");
                
                BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));   
                String line = null;  
                while ((line = in.readLine()) != null) {  
                    System.out.println(line);  
                }  

                File fw=new File("tmp.tmp");
                if (f.delete()){
                    System.out.println("File: " + filename + " deleted");
                }
                if (fw.delete()){
                    System.out.println("Temp file: " + fw.getName() + " deleted");
                }
                
            } catch (FileNotFoundException ex) {
            } catch (IOException ex) {
            } catch (ParseFailedException ex) {
            }
        }
        else {
            System.out.println("Cannot find file");
        }
    }
}
